<?php
namespace app\home\controller;

use think\Controller;
use think\Cookie;

// 公共控制器
use app\common\controller\Home AS HomeController;
use think\process\exception\Failed;

// 帖子控制器
class Post extends HomeController{
    // 构造函数
    public function __construct()
    {
        // 继承底层的控制器构造函数(底层父类构造函数)
        parent::__construct();

        // 定义一个全局模型
        $this->UserModel=model('User.User');
        $this->PostModel=model('Post.Post');
        $this->RecordModel=model('User.Record');
        $this->ConfigModel=model('Config');
        $this->CollectModel=model('User.Collect');
        $this->CommentModel=model('Post.Comment');
        
    }

    // 发帖
    public function add(){
        // 判断是否有post数据
        if($this->request->isPost()){
            // 获取所有的数据
            $params=$this->request->param();

            // 获取参数 如果没有就默认为空
            $vercode=$this->request->param('vercode','');

            // 判断验证码是否正确
            if(!captcha_check($vercode)){
                $this->error('验证码输入错误');
                exit;
            }

            // 统计积分总数
            $state=$this->request->param('state',0);

            // 根据状态查询积分
            $StatePoint=$this->ConfigModel->where(['key'=>"PostState{$state}"])->value("value");
            $StatePoint=is_numeric($StatePoint) ? abs($StatePoint) : 0;

            // 采纳积分
            $AcceptPoint=$this->request->param('point',0);

            // bcadd 解决精度问题导致的计算结果不准确的问题 加法
            $point=bcadd($AcceptPoint,$StatePoint);

            // 判断积分是否充足
            $UserPoint=$this->LoginUser['point'];

            // 让用户积分减发帖积分
            $UpdatePoint=bcsub($UserPoint,$point);

            // 判断积分是否充足
            if($UpdatePoint<0){
                $this->error('积分不足，请先充值');
                exit;
            }

            // 插入帖子表=>插入消费记录表=>更新用户表

            // 开启事务
            $this->PostModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            // 组装帖子表的数据
            $PostData=[
                'title'=>trim($params['title']),
                'content'=>trim($params['content']),
                'point'=>trim($AcceptPoint),
                'state'=>$state,
                'userid'=>$this->LoginUser['id'],
                'cateid'=>trim($params['cateid']),
            ];

            // 插入帖子表
            $PostStatus=$this->PostModel->validate('common/Post/Post')->save($PostData);

            if($PostStatus=== FALSE){
                $this->error($this->PostModel->getError());
                exit;
            }

            // 组装消费记录的数据
            $RecordData=[
                'point'=>$point,
                'state'=>1,
                'userid'=>$this->LoginUser['id']
            ];

            // 判断消费状态
            switch($state){
                case 1:
                    $RecordData['content']="【".$PostData['title']."】采纳积分：<b>".$AcceptPoint."积分</b> 置顶：<b>{$StatePoint}积分</b> - 发布时间：".date("Y-m-d H:i");
                    break;
                case 2:
                    $RecordData['content']="【".$PostData['title']."】采纳积分：<b>".$AcceptPoint."积分</b> 精华：<b>{$StatePoint}积分</b> - 发布时间：".date("Y-m-d H:i");
                    break;
                case 3:
                    $RecordData['content']="【".$PostData['title']."】采纳积分：<b>".$AcceptPoint."积分</b> 热门：<b>{$StatePoint}积分</b> - 发布时间：".date("Y-m-d H:i");
                    break;
                default:
                    $RecordData['content']="【".$PostData['title']."】采纳积分：<b>".$AcceptPoint."积分</b> - 发布时间：".date("Y-m-d H:i");
                    break;
            }

            // 插入消费记录表
            $RecordStatus=$this->RecordModel->validate('common/User/Record')->save($RecordData);

            // 插入失败
            if($RecordStatus===FALSE){
                // 将帖子表插入的数据回滚
                $this->PostModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            // 组装用户表数据
            $UserData=[
                'id'=>$this->LoginUser['id'],
                'point'=>$UpdatePoint
            ];

            // 更新用户表
            $UserStatus=$this->UserModel->isUpdate(true)->save($UserData);

            // 更新失败
            if($UserStatus===FALSE){
                $this->PostModel->rollback();
                $this->RecordModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }

            if($PostStatus === FALSE || $RecordStatus === FALSE || $UserStatus === FALSE){
                $this->PostModel->rollback();
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->error('发布悬赏帖子失败，请重新操作');
                exit;
            }else{
                // 提交事务
                $this->PostModel->commit();
                $this->RecordModel->commit();
                $this->UserModel->commit();
                $this->success('发布悬赏帖子成功，请等待采纳',url('home/index/index'));
                exit;
            }
        }

        // 查询所有的分类
        $catelist=model('Post.Cate')->order('weigh','asc')->select();

        // 获取附加功能
        $statelist=$this->PostModel->state();

        // 赋值
        $this->assign([
            'catelist'=>$catelist,
            'statelist'=>$statelist,
        ]);

        return $this->fetch();
    }

    public function edit(){
        $postid=$this->request->param('postid',0);

        // 根据id查询这个帖子是否存在
        $post=$this->PostModel->find($postid);

        if(!$post){
            $this->error('编辑的帖子不存在');
            exit;
        }

        // 判断登录用户id 和 发帖人的userid 是否相同
        if($post['userid'] != $this->LoginUser['id']){
            $this->error('您无权修改此帖');
            exit;
        }

        // 判断是否有post过来数据
        if($this->request->isPost()){
            // 获取所有的数据
            $params=$this->request->param();

            // 获取参数 如果没有就默认为空
            $vercode=$this->request->param('vercode','');

            // 判断验证码是否正确 如果结果返回true就是正确否则失败
            if(!captcha_check($vercode)){
                $this->error('验证码输入错误');
                exit;
            }

            // 组装数据
            $data=[
                'id'=>$postid,
                'title'=>$params['title'],
                'content'=>$params['content'],
                'cateid'=>$params['cateid']
            ];

            $result=$this->PostModel->isUpdate(true)->save($data);

            if($result===FALSE){
                // 修改失败
                $this->error($this->PostModel->getError());
                exit;
            }else{
                // 修改成功
                $this->success('修改成功',url('home/index/info',['postid'=>$postid]));
                exit;
            }
        }

        // 查询所有的分类
        $catelist=model('Post.Cate')->order('weigh','asc')->select();

        // 赋值
        $this->assign([
            'catelist'=>$catelist,
            'post'=>$post
        ]);

        return $this->fetch();
    }

    // 删除帖子
    public function del(){
        $success=[
            'result'=>false,
            'msg'=>''
        ];

        if($this->request->isPost()){
            $postid=$this->request->param('postid',0);

            // 根据id查询这个帖子是否存在
            $post=$this->PostModel->find($postid);

            if(!$post){
                $this->error('删除的帖子不存在');
                exit;
            }

            // 判断登录用户id和发帖人userid是否相同
            if($post['userid'] != $this->LoginUser['id']){
                $this->error('您无权修改此帖');
                exit;
            }

            // 软删除
            $result=$this->PostModel->destroy($postid);

            if($result===FALSE){
                // 删除失败
                $success['result']=false;
                $success['msg']=$this->PostModel->getError();
            }else{
                // 删除成功
                $success['result']=true;
                $success['msg']='删除成功';
            }

            // 将结果返回给ajax
            return json($success);
        }
    }

    // 用户中心 我的帖子
    public function index(){
        // 分页数据查询
        $postlist=$this->PostModel->where(['userid'=>$this->LoginUser['id']])->order('createtime','desc')->paginate(10);

        $count=$this->PostModel->where(['userid'=>$this->LoginUser['id']])->count();

        // 调试模型执行的最后一条sql语句
        // echo $this->PostModel->getLastSql();
        // exit;

        // var_dump(collection($post)->toArray());
        // exit;

        // 分页调用
        $pagestr=$postlist->render();

        $this->assign([
            'postlist'=>$postlist,
            'count'=>$count,
            'pagestr'=>$pagestr,
        ]);

        return $this->fetch();
    }

    // 用户收藏
    public function collect(){
        $collectlist=$this->CollectModel->with(['user', 'post'])->where(['collect.userid'=>$this->LoginUser['id']])->paginate(10);

        $count=$this->CollectModel->with(['user', 'post'])->where(['collect.userid'=>$this->LoginUser['id']])->count();

        // 分页调用
        $pagestr=$collectlist->render();

        $this->assign([
            'collectlist'=>$collectlist,
            'count'=>$count,
            'pagestr'=>$pagestr,
        ]);

        return $this->fetch();
    }

    public function uncollect(){
        $success = [
            'result' => false,
            'msg' => ''
        ];

        if($this->request->isPost()){
            $postid = $this->request->param('postid', 0);

            //根据id去查询这个帖子是否存在
            $post = $this->PostModel->find($postid);

            if(!$post){
                $this->error('收藏的帖子不存在');
                exit;
            }

            //判断当前这个人是否有收藏过
            $where = [
                'userid' => $this->LoginUser['id'],
                'postid' => $postid
            ];

            $collect = $this->CollectModel->where($where)->find();

            $data = [
                'userid' => $this->LoginUser['id'],
                'postid' => $postid
            ];
            
            if($collect){
                
                $success['result'] = false;
                $result = $this->CollectModel->destroy($data);


                if($result === FALSE){
                    // 添加收藏失败
                    $success['result'] = false;
                    $success['msg'] = $this->CollectModel->getError();
                }else{
                    //添加收藏成功
                    $success['result'] = true;
                    $success['msg'] = '取消成功';
                }
    
                //将结果返回给ajax
                return json($success);
            }

            $success['msg'] = '取消收藏此贴';
            return json($success);
        }
    }

    // 删除评论
    public function commentdel(){
        $success = [
            'result' => false,
            'msg' => ''
        ];

        if($this->request->isPost()){
            $commentid = $this->request->param('id', 0);

            // 根据id去查询这个评论是否存在
            $comment = $this->CommentModel->find($commentid);

            if(!$comment){
                $this->error('评论不存在');
                exit;
            }

            $commentlist=DelComment($commentid,[$commentid]);
            
            $where['id']=array('in',$commentlist);
            
            $result=$this->CommentModel->where($where)->delete(true);

            if($result===FALSE){
                // 添加删除失败
                $success['result'] = false;
                $success['msg'] = $this->CollectModel->getError();
                return json($success);
                
            }else{
                //添加删除成功
                $success['result'] = true;
                $success['msg'] = '删除成功';
                return json($success);
            }
        }
    }
}

?>